Parallel courses [Topological Sort + BFS]¶
Time: O(V + E); Space: O(E); hard
There are N courses, labelled from 1 to N.
We are given relations[i] = [X, Y], representing a prerequisite relationship between course X and course Y: course X has to be studied before course Y.
In one semester you can study any number of courses as long as you have studied all the prerequisites for the course you are studying.
Return the minimum number of semesters needed to study all courses. If there is no way to study all the courses, return -1.
Example 1:
Input: N = 3, relations = [[1,3],[2,3]]
Output: 2
Explanation:
In the first semester, courses 1 and 2 are studied. In the second semester, course 3 is studied.
Example 2:
Input: N = 3, relations = [[1,2],[2,3],[3,1]]
Output: -1
Explanation:
No course can be studied because they depend on each other.
Notes:
1 <= N <= 5000
1 <= len(relations) <= 5000
relations[i][0] != relations[i][1]
There are no repeated relations in the input.
Hints:
Build degrees for each nodes
BFS starts with 0 degrees
When queue is empty, it stops
If we haven’t visited all nodes, the graph has circles
1. Greedy Algorithm with BFS¶
Since we can take as many courses as we want, taking all courses that do not have outstanding prerequisites each semester must be one valid answer that gives a minimum number of semesters needed.
Construct a directed graph and in degree of each node(course).
Add all courses that do not have any prerequisites(in degree == 0) to a queue.
BFS on all neighboring nodes(courses) of the starting courses and decrease their indegrees by 1. If a neighboring course’s indegree becomes 0, it means all its prerequisites are met, add it to queue as this course can be taken in the next semester.
After all neighboring nodes of the courses that are taken in the current semester have been visited, increment semester count by 1. Repeat until the queue is empty.
When doing the BFS, keep a count of courses taken, compare this count with the total number of courses to determine if it is possible to study all courses.
2. DFS with Dynamic Programming¶
Because we have to first take all prerequisites of a course beforing taking it, we know the following two property of this problem. 1. If there is a cycle, there is no way of studying all courses. 2. If there is no cycle, the minimum number of semesters needed to study all courses is determined by the longest acyclic path, i.e, we are looking for the longest acyclic path with each edge’s weight being 1. This is exactly the same problem with Max path value in directed graph. The only difference is the dynamic programming state.
[12]:
import collections
class Solution1(object):
"""
Time: O(|V| + |E|)
Space: O(|E|)
"""
def minimumSemesters(self, N, relations):
"""
:type N: int
:type relations: List[List[int]]
:rtype: int
"""
g = collections.defaultdict(list)
in_degree = [0] * N
for x, y in relations:
g[x-1].append(y-1)
in_degree[y-1] += 1
q = collections.deque([(1, i) for i in range(N) if not in_degree[i]])
result = 0
count = N
while q:
level, u = q.popleft()
count -= 1
result = level
for v in g[u]:
in_degree[v] -= 1
if not in_degree[v]:
q.append((level+1, v))
return result if count == 0 else -1
[15]:
s = Solution1()
N = 3
relations = [[1,3],[2,3]]
assert s.minimumSemesters(N, relations) == 2
N = 3
relations = [[1,2],[2,3],[3,1]]
assert s.minimumSemesters(N, relations) == -1